import requests
import traceback
from common.log import Log
from common.custom_class import NbDict

class Request:
    def __init__(self,url,params=None,data=None,headers=None,json=None,files=None):
        self.url = url
        self.params = params
        self.data = data
        self.headers = headers
        self.json = json
        self.files = files

    def __get_response(self):
        try:
            result = self.req.json()
        except Exception as e:
            result = self.req.text
        else:
            result = NbDict(result)
        return result



    def get(self):
        Log.info("开始发送get请求")
        Log.info("url:【 {} 】,params : 【 {} 】headers:{}", self.url, self.params, self.headers)

        try:
            self.req = requests.get(self.url,params=self.params,headers=self.headers,verify=False)
        except Exception as e:
            Log.error('get接口请求出错,错误信息为{}',traceback.format_exc())
            raise Exception("接口请求不通")

        else:
            return self.__get_response()

    def post(self):
        Log.info("开始发送post请求")
        Log.info("url:【 {} 】,params : 【 {} 】headers:{},data:{},json:{},files:{}",
                 self.url, self.params, self.headers, self.data, self.json, self.files)
        try:
            self.req = requests.post(self.url,params=self.params,
                              data=self.data,json=self.json,
                              files=self.files,
                              headers=self.headers,verify=False)
        except Exception as e:
            Log.error('post接口请求出错,错误信息为{}',traceback.format_exc())
            raise Exception('接口请求不通')

        return self.__get_response()